/**
 * @file 获取图片文件中的二维码信息
 * @date 2019-04-28 19:04:09
 */
import jsQR from 'jsqr';

const urlToImage = (url, callback) => {
    const img = new Image();

    img.addEventListener('load', () => {
        callback(img);
    });

    img.addEventListener('error', () => {
        if (url.indexOf('base64') === -1) {
            urlToImage(`data:image/jpg;base64,${url}`, callback);
        } else {
            callback(null);
        }
    });

    img.src = url;
};

const fileToImage = (file, callback) => {
    if (window.URL) {
        const url = URL.createObjectURL(file);

        urlToImage(url, callback);
    } else if (window.FileReader) {
        const reader = new FileReader();

        reader.addEventListener(
            'load',
            () => {
                urlToImage(reader.result, callback);
            },
            false
        );

        reader.readAsDataURL(file);
    } else {
        callback(null);
    }
};

const getImageQr = img => {
    if (!img || !img.naturalHeight) {
        return null;
    }

    const { naturalHeight: h, naturalWidth: w } = img;
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    canvas.width = w;
    canvas.height = h;

    ctx.drawImage(img, 0, 0, w, h);

    return jsQR(ctx.getImageData(0, 0, w, h).data, w, h);
};

/**
 * 获取图片文件中的二维码信息
 *
 * @param {Object || String} img || base64 || file
 * @returns {Object | Null}
 */
export default img => new Promise(resolve => {
    if (!img) {
        resolve(null);
    } else if (img.name && img.name.toLowerCase() === 'img') {
        resolve(getImageQr(img));
    } else if (img.size && img.type) {
        fileToImage(img, res => {
            resolve(getImageQr(res));
        });
    } else if (typeof img === 'string') {
        urlToImage(img, res => {
            resolve(getImageQr(res));
        });
    } else {
        resolve(null);
    }
});
